package com.sskj.hangqing.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.HangqingBannerBean;
import com.sskj.hangqing.bean.NoticeBean;
import com.sskj.hangqing.box.ZoomOutPageTransformer;
import com.sskj.hangqing.component.DaggerUserDataComponent;
import com.sskj.hangqing.http.HttpConfig;
import com.sskj.hangqing.presenter.HangqingFragmentPresenter;
import com.sskj.hangqing.ui.activity.GuideWebActivity;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.ChineseUtil;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@SuppressWarnings("ALL")
@Route(path = RConfig.HANG_HANGQING)
public class HangqingFragment extends BaseFragment<HangqingFragmentPresenter> {

    @BindView(R2.id.ivLogo)
    ImageView ivLogo;
    @BindView(R2.id.banner)
    Banner banner;
    @BindView(R2.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R2.id.coolRefreshView)
    SmartRefreshLayout coolRefreshView;
    @BindView(R2.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R2.id.layoutZixuanAdd)
    LinearLayout layoutZixuanAdd;
    @BindView(R2.id.llVisitor)
    LinearLayout llVisitor;
    @BindView(R2.id.tvMore)
    TextView tvMore;
    @BindView(R2.id.llFabi)
    LinearLayout llFabi;
    @BindView(R2.id.llAdHelp)
    LinearLayout llAdHelp;
    @BindView(R2.id.llMiner)
    LinearLayout llMiner;
    @BindView(R2.id.ivNotice)
    ImageView ivNotice;
    @BindView(R2.id.segmentTabLayout)
    CommonTabLayout slidingTabLayout;
    private Disposable noticeDispo;
    private NoticeBean noticeList;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private int i;
    private Disposable bannerDispo;
    private String[] titles = {App.INSTANCE.getString(R.string.hangqinghangqingFragment1)/*, App.INSTANCE.getString(R.string.hangqinghangqingFragment2), App.INSTANCE.getString(R.string.hangqinghangqingFragment3)*/};
    private ArrayList<Fragment> fragments;
    private HashMap<Integer, Boolean> coinListMap;
    private int curCoinPos;

    @Override
    protected int getLayoutId() {
        return R.layout.hang_fragment_hangqing;
    }

    @Override
    public HangqingFragmentPresenter getPresenter() {
        return new HangqingFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        ClickUtil.click(llAdHelp, () -> {
            ARouter.getInstance().build(RConfig.HANG_GUIDE_WEB)
                    .withBoolean(Constans.IS_HELP, true)
                    .navigation();
        });

        ClickUtil.click(llFabi, () -> {
            if (AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                LiveDataBus.get().with(RxBusCode.CHANGE_MAIN_TAB, Integer.class)
                        .postValue(3);
            }
        });
        llVisitor.setVisibility(Constans.isInvite? View.VISIBLE:View.GONE);
        ClickUtil.click(tvMore, () -> ARouter.getInstance().build(RConfig.HANG_GONGGAO_LIST).navigation());
        ClickUtil.click(ivNotice, () -> {
            ARouter.getInstance().build(RConfig.HANG_GONGGAO_LIST).navigation();
        });
        ClickUtil.click(llMiner, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }

            ARouter.getInstance().build(RConfig.MINER_MAIN).navigation();
        });
        ClickUtil.click(200, layoutZixuanAdd, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.HANG_ZIXUAN_ADD).navigation();
        });
        ClickUtil.click(200, llVisitor, () -> {
            ARouter.getInstance().build(RConfig.MINE_INVITE).navigation();
        });
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);

                Glide.with(context)
                        .load(path)
                        .apply(RequestOptions
                                .bitmapTransform(new RoundedCorners(30))
                                .error(R.mipmap.hang_default_banner))
                        .into(imageView);
            }
        });
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.libTextGray));
            return textView;
        });

        fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.HANG_FRAGMENT_COIN_LIST_WRAP).withBoolean(Constans.IS_UP_DOWN, true).navigation());
//        fragments.add((Fragment) ARouter.getInstance().build(RConfig.HANG_FRAGMENT_COIN_LIST_WRAP).withBoolean("isNew", true).navigation());
//        fragments.add((Fragment) ARouter.getInstance().build(RConfig.HANG_FRAGMENT_COIN_LIST_WRAP).withBoolean("isSelf", true).navigation());
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayout, fragments.get(0))
                .commitAllowingStateLoss();
        coinListMap = new HashMap<>();
        coinListMap.put(0, true);
        curCoinPos = 0;
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.hangqinghangqingFragment1), 0, 0));
//        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.hangqinghangqingFragment2), 0, 0));
//        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.hangqinghangqingFragment3), 0, 0));
        slidingTabLayout.setTabData(tabItems);
        slidingTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (coinListMap.get(position) != null && coinListMap.get(position)) {
                    getChildFragmentManager()
                            .beginTransaction()
                            .hide(fragments.get(curCoinPos))
                            .show(fragments.get(position))
                            .commitAllowingStateLoss();

                } else {
                    getChildFragmentManager()
                            .beginTransaction()
                            .add(R.id.frameLayout, fragments.get(position))
                            .hide(fragments.get(curCoinPos))
                            .show(fragments.get(position))
                            .commitAllowingStateLoss();
                    coinListMap.put(position, true);

                }
                curCoinPos = position;
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        slidingTabLayout.setCurrentTab(0);
//        viewPager.setCurrentItem(1);
//        viewPager.setSlide(false);
    }

    @Override
    public void initData() {

        mPresenter.getBanner();
        mPresenter.getNotice();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        coolRefreshView.setEnableLoadMore(false);
        coolRefreshView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mPresenter.getBanner();
                mPresenter.getNotice();
            }
        });
    }

    public void updateBanner(List<HangqingBannerBean> data) {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.finishRefresh();
        }
        if (banner == null) {
            return;
        }

        ArrayList<String> strings = new ArrayList<>();
        for (HangqingBannerBean bannerItem : data) {
            strings.add(HttpConfig.BASE_IMG_URL + (ChineseUtil.isChinese() ? bannerItem.getImgUrl() : bannerItem.getImgUrlUs()));
        }
        List<Integer> temp = new ArrayList<>();
        temp.add(R.mipmap.hang_default_banner);
        banner.setImages(strings.size() == 0 ? temp : strings);
        banner.setOffscreenPageLimit(3);
        banner.setPageTransformer(false, new ZoomOutPageTransformer());
        banner.start();
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(noticeDispo);
        DisposUtil.close(bannerDispo);
        super.onDestroy();
    }


    public void updateNotice(List<NoticeBean> notice) {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.finishRefresh();
        }
        if (tvNotice != null) {
            if (notice.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeList = notice.get((int) (i % notice.size()));
                                tvNotice.setText(noticeList.getTitle());
                                ClickUtil.click(tvNotice, () -> {
//                                    ARouter.getInstance()
//                                            .build(RConfig.HANG_GUIDE_WEB)
//                                            .greenChannel()
//                                            .withBoolean(Constans.IS_HANGQING_NOTICE, true)
//                                            .withString(Constans.HEAD, App.INSTANCE.getString(R.string.hangqinggonggaoListActivity2))
//                                            .withString(Constans.TITLE, noticeList.getTitle())
//                                            .withString(Constans.CONTENT, noticeList.getDetails())
//                                            .withString(Constans.TIME, noticeList.getCreateTime())
//                                            .navigation();
                                    Intent intent = new Intent(getContext(), GuideWebActivity.class);
                                    intent.putExtra(Constans.IS_HANGQING_NOTICE, true);
                                    intent.putExtra(Constans.HEAD, App.INSTANCE.getString(R.string.hangqinggonggaoListActivity2));
                                    intent.putExtra(Constans.TITLE, noticeList.getTitle());
                                    intent.putExtra(Constans.CONTENT, noticeList.getDetails());
                                    intent.putExtra(Constans.TIME, noticeList.getCreateTime());
                                    startActivity(intent);
                                });
                            }
                        }, System.out::println);
            }
        }
    }
}
